import fs from 'fs'
import path from 'path'
import createKnex, { Knex } from 'knex'

let INSTANCE: any = null

if (import.meta.server) {
  const rootDir = process.cwd()

  const dir = path.resolve(rootDir, 'database/storage')

  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true })
  }

  const sqlite3: Knex.Config = {
    client: 'sqlite3',
    debug: false,
    useNullAsDefault: true,
    connection: {
      filename: `${dir}/data.sqlite`,
    },
  }

  INSTANCE = createKnex(sqlite3)
}

export default INSTANCE
